package com.musiklegal;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class AnotherSong extends Activity 
{
	ListView lvc;
	TextView tv;
	int offset=0;
	public static String merchantKey;
	String temp="fachr1";
	static String name; 
	ProgressDialog dialog;
	boolean loading=false;
	HttpClient tinfo; 
	HttpGet gets;
	HttpResponse hrep;
	HttpEntity trinfo;
	SAXParserFactory spf;
	CatalogueParser cp;
	SAXParser sp ;
	XMLReader xr;
	Address addres;
  	public static String artistId =null;
	List<DataSong> listSong;
	Handler h;
	ProgressBar pb;
	EditText srctxt ;
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		h = new Handler();
		setContentView(R.layout.catalogue);
		listSong = new ArrayList<DataSong>(25);
		if(MusikLegal.internet(getApplicationContext())){
		tinfo = new DefaultHttpClient(); 
		cp = new CatalogueParser();
		srctxt= (EditText) findViewById(R.id.search);
		addres = new Address("http://secure.musiklegal.com/?action=catalogue&method=get&artist_id="+artistId+"&api_key="+merchantKey+"&limit=25",offset,"");
		pb = (ProgressBar) findViewById(R.id.loading);
		pb.setVisibility(View.VISIBLE);
		
		new Thread(new Runnable(){

			public void run() {
			
				
						
						try {
							catalogue();
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							
							e.printStackTrace();
						}
						
						
				        if(!MusikLegal.internet(getApplicationContext()))
				        {
					        h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
								}});
				        }	
						
					
				
			}}).start();
		
        
	}
	}
	
	public void onResume()
	{
		super.onResume();
		if(!MusikLegal.internet(getApplicationContext()))
		{
			finish();
		}
		
	}
	
	void catalogue() throws ClientProtocolException, IOException, ParserConfigurationException, SAXException
	{
		
			tv = (TextView)findViewById(R.id.onlinestore);
			
		 	lvc=(ListView)findViewById(R.id.CatView);
			
			 InterfaceAdapter adapter2 = new InterfaceAdapter(this,listSong); 
			 adapter2.notifyDataSetChanged();
			 lvc.setAdapter(adapter2);
			 lvc.setItemsCanFocus(true);
			 tinfo = new DefaultHttpClient();
			 gets = new HttpGet(addres.toString());
			 hrep = tinfo.execute(gets);
			 trinfo = hrep.getEntity();
			 spf = SAXParserFactory.newInstance();
			 sp = spf.newSAXParser();
			 xr = sp.getXMLReader();
		 	xr.setContentHandler(cp);
			xr.parse(retrieveInputStream(trinfo));
			listSong.addAll(cp.catl);
			cp.catl.clear();
			h.post(new Runnable(){

				public void run() {
					pb.setVisibility(View.GONE);
					lvc.invalidateViews();
					
				}});
			
			
			 lvc.setOnScrollListener(new OnScrollListener(){

				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					int lastitem = firstVisibleItem + visibleItemCount;
					if(lastitem == totalItemCount-1)
						{
						
						
						new Thread(new Runnable(){

							public void run() {
							
								
										if(!loading&&offset+24<=listSong.size()){
					               			 try {
					               				 loading=true;
					               				
					               				 offset+=25;
					               				 
					    						 addres.offset=offset;
					               				 tinfo = new DefaultHttpClient();
					    						 gets = new HttpGet(addres.toString());
												hrep = tinfo.execute(gets);
												trinfo = hrep.getEntity();
						               			 spf = SAXParserFactory.newInstance();
						               			 sp = spf.newSAXParser();
						               			xr = sp.getXMLReader();
						               			xr.setContentHandler(cp);
						               			xr.parse(retrieveInputStream(trinfo));
						               			listSong.addAll(cp.catl);
						               			cp.catl.clear();
						               			
						               			
						               			
											} catch (ClientProtocolException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (ParserConfigurationException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (SAXException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
											finally
											{
												loading=false;
											}
											
											
											}
										
									
								
							}}).start();
						
						//showDialog(0);
						
						}
					
				}

				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
				}});
			 
			 lvc.setOnItemClickListener(new OnItemClickListener() 
		        {
		          public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
		          {
		        	  try{
		        		  	TrackInfo.ds = (DataSong) lvc.getItemAtPosition(position);
		        			 TrackInfo.fromCatalogue=true;
		        			 TrackInfo.fromFriend=false;
		        			 TrackInfo.mercapi=merchantKey;
		        			 Intent i = new Intent(getApplicationContext(), TrackInfo.class);
		        			 startActivity(i);
		        	  }
		        	  catch (Exception e) {
		              }
		        	  }
		        });
			 
			 Button search = (Button) this.findViewById(R.id.src);
			 search.setOnClickListener(new OnClickListener() 
             {
                   public void onClick(View v) 
                   {
                	  // showDialog(0);
                	   new Thread(new Runnable(){

               			public void run() {
               			
               				
               						
               						try
                             	   {
                             		   
                           			 	String srch = srctxt.getText().toString();
                           			 	tinfo = new DefaultHttpClient();
                           			 	offset=0;
                           			 	if(srch.compareTo("")==0)
                       			 		{                         			 			
                       			 			addres.filter="";
                      			 		}
                           			 	else
                           			 		addres.filter=srch;
                           			 	
                             		     gets = new HttpGet(URLEncoder.encode(addres.toString()));
                             		     
                             		     //URLEncodeForm uef = new URLEncodedForm(addres.toString());
                             		     listSong.clear();
                             		     
                             			 hrep = tinfo.execute(gets);
                             			 trinfo = hrep.getEntity();
                             			 spf = SAXParserFactory.newInstance();
                             			 sp = spf.newSAXParser();
                             			 xr = sp.getXMLReader();
                                   	
                             			xr.setContentHandler(cp);
                             			xr.parse(retrieveInputStream(trinfo));
                             			listSong.addAll(cp.catl);
                             			cp.catl.clear();
                             			h.post(new Runnable(){

                           					public void run() {
                             			lvc.invalidateViews();
                           					}});
                             			
                             			}
                             	   catch (Exception e) {
                             		   
               		              }
                             	   finally{
                             		  h.post(new Runnable(){

                         					public void run() {
                             		   removeDialog(0);
                         					}});
                             	   }
               						
               					
               				
               			}}).start();
                	   
                	   
                   }
             });
		
	}
	
	
	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  }
	
	 protected Dialog onCreateDialog(int id) {
	        switch (id) {
	              case 0: {
	                    dialog = new ProgressDialog(this);
	                    dialog.setMessage("Loading...");
	                    dialog.setIndeterminate(true);
	                    dialog.setCancelable(true);
	                    return dialog;                   
	              }
	        }
	        return null;
	  }
	public void onDestroy()
	{
		merchantKey=null;
		super.onDestroy();
	}
}
